package com.qzdsoft.erpcloud.service.sys.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.qzdsoft.erpcloud.domain.basic.BasicUser;
import com.qzdsoft.erpcloud.domain.sys.LoginUser;
import com.qzdsoft.erpcloud.domain.sys.SysAgentUser;
import com.qzdsoft.erpcloud.domain.sys.SysUser;
import com.qzdsoft.erpcloud.mapper.basic.BasicUserMapper;
import com.qzdsoft.erpcloud.mapper.sys.SysAgentUserMapper;
import com.qzdsoft.erpcloud.mapper.sys.SysUserMapper;
import com.qzdsoft.erpcloud.service.sys.RedisService;
import com.qzdsoft.erpcloud.service.sys.SysLoginService;
import com.qzdsoft.erpcloud.service.sys.SysUserService;
import com.qzdsoft.erpcloud.vo.query.basic.BasicUserEditInfo;
import com.qzdsoft.erpcloud.vo.query.basic.BasicUserInfo;
import com.qzdsoft.erpcloud.vo.sys.SysUserQueryParam;
import com.qzdsoft.utils.ExceptionUtil;
import com.qzdsoft.utils.JsonUtils;
import com.qzdsoft.utils.StringUtil;
import com.qzdsoft.utils.SysUtils;
import com.qzdsoft.utils.enums.CommonStatusEnum;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;

/**
 * Created by Yang
 */
@Service
public class SysUserServiceImpl implements SysUserService {
	private static final Logger logger = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;
    
    @Autowired
    private SysAgentUserMapper sysAgnrtUserMapper;
    
    @Autowired
    private BasicUserMapper basicUserMapper;

    @Value("${login.validate}")
    private boolean loginValidate;

    @Autowired
    private SysLoginService sysLoginService;
    
    @Autowired
    private RedisService redisService;

    @Override
    public SysUser selectById(Integer id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }
    
    @Override
    public BasicUserInfo selectBasicUserById(Integer id) {
        return basicUserMapper.selectBasicUserById(id);
    }

//    @Override
//    public Response saveOrUpd(SysUser sysUser) {
//        if(null != sysUser.getId()){
//            sysUserMapper.updateByPrimaryKey(sysUser);
//        } else {
//
//            if(null == sysUser.getCompany_id()){
//                sysUser.setCompany_id(SystemConstant.companyIdGg);
//            }
//
//            sysUserMapper.insert(sysUser);
//        }
//        return Response.success(null);
//    }

    @Override
    public Response del(Integer id) {
        BasicUser sysUser = basicUserMapper.selectByPrimaryKey(id);
        if(sysUser == null) {
        	logger.error("系统用户删除错误，id={}",id);
        	throw new RuntimeException("系统用户删除错误，根据id未查询到数据，可能用户不存在！");
        }
        sysUser.setId(id);
        sysUser.setStatus(CommonStatusEnum.stop.getKey().toString());
        basicUserMapper.updateByPrimaryKey(sysUser);
        return Response.success(null);
    }


//    @Override
//    public List<Map<String, Object>> selectData(String account, String name, Integer agent, Integer status, Integer companyId, Integer roleId, Integer start, Integer pageSize) {
//        return sysUserMapper.selectData(account, name, agent, status, companyId, roleId, start, pageSize);
//    }
    
    @Override
    public LoginUser getUser(Integer uid)
    {
        Object user = redisService.get(SysUtils.redisUserSessionId(uid));
        if(user!=null) {
            return JsonUtils.jsonToPojo(user.toString(), LoginUser.class);
        }
        if(loginValidate==false) {
            return new LoginUser(1, 1, 1, "1", "超级管理员", "18688949884");
        }
        return null;
    }

	@Override
	public LayTableResponse<BasicUserInfo> selectData(SysUserQueryParam info) {
		logger.debug("page={},limit={}",info.getPage(),info.getLimit());
		try{
			PageHelper.startPage(info.getPage(), info.getLimit());
			List<BasicUserInfo> lists = basicUserMapper.selectData(info);
			logger.debug("id={}"+lists.get(0).getName());
			return new LayTableResponse<BasicUserInfo>(lists);
		}catch(Exception e){
			e.printStackTrace();
			ExceptionUtil.getStackTrace(e);
		}
		return new LayTableResponse<BasicUserInfo>(null);
	}

	@Override
	@Transactional
	public Response edit_execute(BasicUserEditInfo info) {
		if(null != info.getId()) {//修改
			BasicUser user = basicUserMapper.selectByPrimaryKey(info.getId());
			if(user == null) {
				logger.error("系统用户修改保存错误:根据id查询user未空,id={}",info.getId());
				throw new RuntimeException("系统用户保存报错，根据id没有查找到user，可能用户不存在！");
			}
			if(!StringUtil.isEmpty(info.getName())) {
				user.setName(info.getName());
			}
			if(!StringUtil.isEmpty(info.getEmail())) {
				user.setEmail(info.getEmail());
			}
			if(!StringUtil.isEmpty(info.getPhone())) {
				user.setPhone(info.getPhone());
			}
			if(!StringUtil.isEmpty(info.getStatus())) {
				user.setStatus(info.getStatus());
			}
			if(!StringUtil.isEmpty(info.getRemark())) {
				user.setRemark(info.getRemark());
			}
			if(!StringUtil.isEmpty(info.getType())) {
				user.setType(info.getType());;
			}
			if(!StringUtil.isEmpty(info.getCompanyId())) {
				user.setCompanyId(info.getCompanyId());
			}
			if(!StringUtil.isEmpty(info.getRoleId())) {
				user.setRoleId(info.getRoleId());
			}
//			if(!StringUtils.isNoneBlank(info.getPassword())) {
//				info.setPassword(SysUtils.string2MD5(info.getPassword()));
//			}
			int bcount = basicUserMapper.updateByPrimaryKeySelective(info);
			if(bcount !=1) {
				logger.error("更新basu_user表的条目不正确，id={}",info.getId());
				throw new RuntimeException("数据保存错误，可能存在重复数据，id={}"+info.getId());
			}
			//sys_agent_user
			if(info.getType().equals(2+"")) {
				SysAgentUser agenUser = sysAgnrtUserMapper.selectByPrimaryKey(info.getId());
				if(agenUser == null) {//新增
					logger.debug("sys_agent_user新增保存,id={}",info.getId());
					SysAgentUser agen = new SysAgentUser();
					if(!StringUtil.isEmpty(info.getFirst())) {
						agen.setFirst(info.getFirst());
					}
					if(!StringUtil.isEmpty(info.getSecond())) {
						agen.setSecond(info.getSecond());
					}
					if(!StringUtil.isEmpty(info.getThree())) {
						agen.setThree(info.getThree());
					}
//					agen.setBalance(0);
					agen.setId(info.getId());
					sysAgnrtUserMapper.insert(agen);
				}else{
					//修改保存
					if(!StringUtil.isEmpty(info.getFirst())) {
						agenUser.setFirst(info.getFirst());
					}
					if(!StringUtil.isEmpty(info.getSecond())) {
						agenUser.setSecond(info.getSecond());
					}
					if(!StringUtil.isEmpty(info.getThree())) {
						agenUser.setThree(info.getThree());
					}
					int acount = sysAgnrtUserMapper.updateByPrimaryKey(agenUser);
					if(acount != 1) {
						logger.error("更新sys_agent_user错误，id=",info.getId());
						throw new RuntimeException("数据保存错误，可能存在重复数据,id={}"+info.getId());
					}
				}
			}
		}else {//新增
			BasicUser nuser = new BasicUser();
			if(!StringUtil.isEmpty(info.getName())) {
				nuser.setName(info.getName());
			}
			if(!StringUtil.isEmpty(info.getEmail())) {
				nuser.setEmail(info.getEmail());
			}
			if(!StringUtil.isEmpty(info.getPhone())) {
				nuser.setPhone(info.getPhone());
			}
			if(!StringUtil.isEmpty(info.getStatus())) {
				nuser.setStatus(info.getStatus());
			}
			if(!StringUtil.isEmpty(info.getRemark())) {
				nuser.setRemark(info.getRemark());
			}
			if(!StringUtil.isEmpty(info.getType())) {
				nuser.setType(info.getType());;
			}
			if(!StringUtil.isEmpty(info.getCompanyId())) {
				nuser.setCompanyId(info.getCompanyId());
			}
			if(!StringUtil.isEmpty(info.getRoleId())) {
				nuser.setRoleId(info.getRoleId());
			}
			if(!StringUtil.isEmpty(info.getPassword())) {
				nuser.setPassword(SysUtils.string2MD5(info.getPassword()));
			}
			nuser.setCtime(new Date());
			int ncout = basicUserMapper.insert(nuser);
			if(ncout!=1) {
				logger.error("basic_user插入记录错误，",nuser);
				throw new RuntimeException("系统用户新增错误,条目="+ncout);
			}
			if(info.getType().equals(2+"")) {
				SysAgentUser nAUser = new SysAgentUser();
				nAUser.setId(nuser.getId());
				if(!StringUtil.isEmpty(info.getFirst())) {
					nAUser.setFirst(info.getFirst());
				}
				if(!StringUtil.isEmpty(info.getSecond())) {
					nAUser.setSecond(info.getSecond());
				}
				if(!StringUtil.isEmpty(info.getThree())) {
					nAUser.setThree(info.getThree());
				}
				sysAgnrtUserMapper.insert(nAUser);
			}
		}
		return Response.success("保存成功!");
	}

	@Override
	public Response pwdsave(Integer id, String opwd, String npd, String npda) {
		if(StringUtils.isNotBlank(opwd) && StringUtils.isNotBlank(npd) && StringUtils.isNotBlank(npda)) {
    		if(npd.equals(npda)) {
    			BasicUser user = basicUserMapper.selectByPrimaryKey(id);
    			String pwd = user.getPassword();
    			if(!pwd.equals(SysUtils.string2MD5(opwd))){
                    return Response.error("输入的旧密码不正确");
                }
    			user.setPassword(SysUtils.string2MD5(npd));
    			basicUserMapper.updateByPrimaryKey(user);
    		}else{
    			return Response.error("两次输入密码不一致");
    		}
    		
    	}else{
    		return Response.error("请输入密码");
    	}
		return new Response(ResultEnum.SUCCESS);
	}
	
	
}
